<template>
  <div class>
    <div class="card tr mb2">
      <el-tooltip content="显示字段筛选" placement="bottom" effect="light">
        <el-popover placement="bottom" width="200" trigger="click">
          <el-checkbox
            :indeterminate="isIndeterminate"
            v-model="checkAll"
            @change="handleCheckAllChange"
          >全选</el-checkbox>
          <el-checkbox-group v-model="showItemList" @change="handleCheckedChange">
            <el-checkbox v-for="(item,key) in allItemList" :key="key" :label="item">{{item.name}}</el-checkbox>
          </el-checkbox-group>
          <el-button slot="reference" icon="el-icon-menu" size="mini" type="primary" circle></el-button>
        </el-popover>
      </el-tooltip>
      <el-tooltip content="展开/收起表单" placement="bottom" effect="light">
        <el-button
          icon="el-icon-search"
          @click="formShow= !formShow"
          size="mini"
          type="primary"
          circle
        ></el-button>
      </el-tooltip>
      <el-tooltip content="下载当前表格数据" placement="bottom" effect="light">
        <el-button
          icon="el-icon-download"
          @click="handleDownload"
          size="mini"
          type="primary"
          circle
        ></el-button>
      </el-tooltip>
      <el-button size="mini" type="primary" icon="el-icon-plus" @click="showDialog">添加</el-button>
    </div>

    <div class="card form" v-show="formShow">
      <el-form
      size="mini"
        :style="style"
        :model="ruleForm"
        ref="ruleForm"
        inline
        label-width="100px"
        class="demo-ruleForm"
      >
        <div class="icon-arrow" v-if="folding">
          <i
            @click="offForm=!offForm"
            :title="offForm?'展开表单':'收起表单'"
            :class="offForm?'el-icon-arrow-down':'el-icon-arrow-up'"
          ></i>
        </div>

        <my-form-item label="职务名称" prop="dutyName">
          <el-input v-model="ruleForm.dutyName" size="mini"></el-input>
        </my-form-item>
        <my-form-item label="状态" prop="dutyEnabledState">
          <el-select v-model="ruleForm.dutyEnabledState" size="mini" clearable placeholder="请选择">
            <el-option
              v-for="item in dutyEnabledState"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </my-form-item>
        <my-form-item>
          <el-button size="mini" type="primary" @click="submitForm('ruleForm')">查询</el-button>
          <el-button size="mini" @click="resetForm('ruleForm')">重置</el-button>
        </my-form-item>
      </el-form>
    </div>

    <el-table ref="dragTable" row-key="id" :data="tableData" border style="width: 100%">
      <el-table-column type="index" width="60px" align="center" fixed="left" label="序号"></el-table-column>
      <el-table-column v-for="(item,index) in allItemList" :key="index" :label="item.name" :prop="item.key" v-if="item.show">
      </el-table-column>

      <el-table-column label="操作" width="260px" fixed="right" align="center">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" class="el-icon-edit" @click="showEditDialog(scope.$index, scope.row)">编辑</el-button>
          <el-button type="primary" size="mini" @click="showUser(scope.row)">用户</el-button>
          <el-button size="mini" type="success" @click="privilege(scope.row)">权限</el-button>
          <el-button size="mini" type="danger" class="el-icon-delete" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-card style="text-align:right;">
      <el-pagination
        @size-change="sizeChange"
        @current-change="currentChange"
        :current-page="currentPage"
        :page-sizes="[ 10, 20,30, 40]"
        :page-size="pageSize"
        background
        layout="total, sizes, prev, pager, next"
        :total="total"
      ></el-pagination>
    </el-card>
    <!-- --------------------------------------------------------添加弹出框 -->
    <el-dialog title="新增管理" width="300px" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
      <el-form size="mini" :model="form" ref="addForm" :rules="rules">
        <my-form-item label="职务名称" :label-width="formLabelWidth" prop="dutyName">
          <el-input v-model="form.dutyName" autocomplete="off"></el-input>
        </my-form-item>
        <my-form-item label="状态" :label-width="formLabelWidth" prop="dutyEnabledState">
          <el-switch
            v-model="switchValue"
            active-text="启用"
            inactive-text="禁用"
            active-value="1"
            inactive-value="0"
          ></el-switch>
        </my-form-item>
        <my-form-item label="职务介绍" :label-width="formLabelWidth" prop="dutyIntroduce">
          <el-input v-model="form.dutyIntroduce" autocomplete="off"></el-input>
        </my-form-item>
        <my-form-item label="备注" :label-width="formLabelWidth" prop="remark">
          <el-input v-model="form.remark" autocomplete="off"></el-input>
        </my-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="dialogFormVisible = false">取 消</el-button>
        <el-button size="mini" type="primary" @click="handleAdd()">确 定</el-button>
      </div>
    </el-dialog>
    <!-- --------------------------------------------------------编辑弹出框 -->
    <el-dialog title="编辑管理" width="300px" :visible.sync="dialogEditVisible" :close-on-click-modal="false">
      <el-form size="mini" :model="editForm" ref="editForm" :rules="rules">
        <my-form-item label="职务名称" :label-width="formLabelWidth" prop="dutyName">
          <el-input v-model="editForm.dutyName" autocomplete="off"></el-input>
        </my-form-item>
        <my-form-item label="状态" :label-width="formLabelWidth" prop="dutyEnabledState">
          <el-switch
            v-model="switchEditValue"
            active-text="启用"
            inactive-text="禁用"
            active-value="1"
            inactive-value="0"
          ></el-switch>
        </my-form-item>
        <my-form-item label="职务介绍" :label-width="formLabelWidth" prop="dutyIntroduce">
          <el-input v-model="editForm.dutyIntroduce" autocomplete="off"></el-input>
        </my-form-item>
        <my-form-item label="备注" :label-width="formLabelWidth" prop="remark">
          <el-input v-model="editForm.remark" autocomplete="off"></el-input>
        </my-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="dialogEditVisible = false">取 消</el-button>
        <el-button size="mini" type="primary" @click="handleEdit()">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="用户" :visible.sync="dialogUser" width="80%">
      <div class="card" style>
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="dialogAllUser=true">添加</el-button>
      </div>
      <el-table :data="userTableData" border style="width: 100%">
        <el-table-column type="index" width="60px" align="center" fixed="left" label="序号"></el-table-column>
        <el-table-column align="center" prop="username" label="用户名"></el-table-column>
        <el-table-column align="center" prop="realName" label="真实姓名"></el-table-column>
        <el-table-column align="center" prop="mobile" label="手机号码"></el-table-column>
        <el-table-column align="center" prop="telephone" label="电话号码"></el-table-column>
        <el-table-column align="center" prop="email" label="电子邮箱"></el-table-column>
        <el-table-column align="center" label="操作" width="100">
          <template slot-scope="scope">
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="delUser(scope.$index, scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="card" style="text-align:right;">
        <el-pagination
          @size-change="sizeChange1"
          @current-change="currentChange1"
          :current-page="currentPage1"
          :page-sizes="[ 10, 20,30, 40]"
          :page-size="pageSize1"
          background
          layout="total, sizes, prev, pager, next"
          :total="total1"
        ></el-pagination>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogUser = false" size="mini">取 消</el-button>
        <el-button type="primary" @click="dialogUser = false" size="mini">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="所有用户" width="80%" :visible.sync="dialogAllUser" >
      <users ref="user" />
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" size="mini" @click="addUserOk">确 定</el-button>
      </span>
    </el-dialog>
    <qx-dialog ref="qxDL" :dutyId="dutyId"></qx-dialog>
  </div>
</template>

<script>
import {getUserListByDutyId,addDutyUser,delDutyUser} from "./../district/function"

import users from "@/components/checkUser/uesrs.vue";
import qxDialog from "./components/qxgl";
const defaultFormThead = [
  { key: "dutyName", name: "职务名称",show:true },
  { key: "dutyIntroduce", name: "职务介绍",show:true },
  { key: "remark", name: "备注",show:true },
  {
    key: "dutyEnabledState",
    name: "状态",show:true
  }
];
export default {
  components:{
    users,
    qxDialog
  },
  data() {
    return {
      key: 1,
      showItemList: defaultFormThead,
      allItemList: defaultFormThead,
      checkAll: true,
      isIndeterminate: false,
      formShow: false,
      dutyEnabledState: [
        {
          value: "1",
          label: "启用"
        },
        {
          value: "0",
          label: "禁用"
        }
      ],
      users: [],
      initZzjg: [],
      switchValue: "1",
      switchEditValue: "1",
      sysOrganList: [],
      userTableData:[],
       total1: 0,
      pageSize1: 10,
      currentPage1: 1,
      dialogAllUser:false,
      dutyId:'',
      dialogUser:false,
      dialogFormVisible: false,
      dialogEditVisible: false,
      offForm: true, //是否折叠
      folding: false, //表单是否超过一行
      formLabelWidth: "80px",
      tableData: [],
      total: 0,
      pageSize: 10,
      currentPage: 1,
      ruleForm: {
        dutyCode: "",
        dutyName: "",
        dutyType: "",
        dutyIntroduce: "",
        dutyEnabledState: "",
        remark: ""
      },
      style: {},
      rules: {
        dutyName: [
          { required: true, message: "请输入职务名称", trigger: "blur" }
        ]
      },
      form: {
        dutyCode: "",
        dutyName: "",
        dutyType: "",
        dutyIntroduce: "",
        dutyEnabledState: "",
        remark: ""
      },
      editForm: {
        id: "",
        //  dutyCode:'',
        dutyName: "",
        dutyType: "",
        dutyIntroduce: "",
        dutyEnabledState: "",
        remark: ""
      }
    };
  },
  mounted() {
    this.init();
    this.getusers();
    let formHeight = this.$refs.ruleForm.$el.clientHeight;
    if (formHeight > 62) {
      this.folding = true;
      this.style = {
        height: "62px",
        overflow: "hidden"
      };
    } else {
      this.folding = false;
      this.style = {
        height: "auto",
        overflow: "hidden"
      };
    }
  },
  computed: {},
  watch: {
    offForm: function(v) {
      if (v) {
        this.style = {
          height: "62px",
          overflow: "hidden"
        };
      } else {
        this.style = {
          height: "auto",
          overflow: "hidden"
        };
      }
    },
    showItemList(valArr) {
        for (let key in this.allItemList) {
          this.allItemList[key].show = false;
          for (let key1 in valArr) {
            if (this.allItemList[key].key == valArr[key1].key) {
              this.allItemList[key].show = true;
            }
          }
        }
      this.$nextTick(() => {
        this.$refs.dragTable.doLayout();
      });
    }
  },
  methods: {
    sizeChange1(n) {
      this.pageSize1 = n;
      this.getUserListByDutyId();
    },
    currentChange1(n) {
      this.currentPage1 = n;
      this.getUserListByDutyId();
    },
    handleCheckedChange(value) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === defaultFormThead.length;
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < defaultFormThead.length;
    },
    handleCheckAllChange(val) {
      this.showItemList = val ? defaultFormThead : [];
      this.isIndeterminate = false;
    },
    handleDownload() {
      this.downloadLoading = true;
      import("@/vendor/Export2Excel").then(excel => {
        const tHeader = ["序号", "职务名称", "职务介绍", "备注","状态"];
        const filterVal = [
          "id",
          "dutyName",
          "dutyIntroduce",
          "remark",
          "dutyEnabledState"
        ];
        const data = this.formatJson(filterVal, this.tableData);
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: "table-list-duty"
        });
        this.downloadLoading = false;
      });
    },
    formatJson(filterVal, jsonData) {
      let i = 0
      return jsonData.map(v =>
        filterVal.map(j => {
          if (j === "id") {
            i++
            return i
          } else {
            return v[j];
          }
        })
      );
    },

    getPremLevel(val) {
      this.sysOrganList = val;
    },
    getEditPremLevel(val) {
      this.sysOrganList = val;
    },
    sizeChange(n) {
      this.pageSize = n;
      this.init();
    },
    currentChange(n) {
      this.currentPage = n;
      this.init();
    },
    init() {
      let params = {
        pageNum: this.currentPage,
        pageSize: this.pageSize,
        ...this.ruleForm
      };
      this.$api.formPost("/api/auth/sysDuty/doGetList", params).then(res => {
        if (res.retHead.code == "0000000") {
          this.tableData = res.retBody.list;
          this.total = res.retBody.total;
          this.currentPage = res.retBody.pageNum;
        }
      });
    },
    showDialog() {
      this.dialogFormVisible = true;
      this.form = {};
    },
    showEditDialog(index, row) {
      console.log(row);
      this.initZzjg = [];
      let list = row.sysDutyOrganList;
      for (let key in list) {
        this.initZzjg.push(list[key].organId);
      }
      this.editForm.id = row.id;
      this.editForm.dutyName = row.dutyName;
      this.switchEditValue = row.dutyEnabledState == "启用" ? "1" : "0";
      this.editForm.dutyType = row.dutyType;
      this.editForm.dutyIntroduce = row.dutyIntroduce;
      this.editForm.remark = row.remark;
      this.$nextTick(() => {
        this.$refs.editZzjg.resetChecked();
      });
      this.dialogEditVisible = true;
    },
    showUser(row) {
      this.dialogUser = true;
      let id = row.id;
      this.dutyId = id;
      this.getUserListByDutyId();
    },
    addUserOk() {
      let checkedUsers = this.$refs.user.selectedTableData;
      let userids = "";
      checkedUsers.forEach(item => {
        userids += item.id + ",";
      });

      let params = {
        dutyId: this.dutyId,
        userIds: userids
      };
      addDutyUser(params).then(res => {
        this.dialogAllUser = false;
        if (res.retHead.code == "0000000") {
          this.$message.success(res.retHead.message);
          this.getUserListByDutyId()
        } else {
          this.$message.error(res.retHead.message);
        }
      });
    },
    delUser(index, row) {
      let params = {
        dutyId: this.dutyId,
        userId: row.id
      };
      delDutyUser(params).then(res => {
        if (res.retHead.code == "0000000") {
          this.$message.success(res.retHead.message);
          this.getUserListByDutyId();
        } else {
          this.$message.error(res.retHead.message);
        }
      });
    },
    privilege(row){
      this.dutyId = row.id;
      this.$refs.qxDL.qxDialogShow = true;
    },
    getUserListByDutyId() {
      let params = {
        pageNum: this.currentPage1,
        pageSize: this.pageSize1,
        dutyId: this.dutyId
      };
      getUserListByDutyId(params).then(res => {
        console.log(res);
        if (res.retHead.code == "0000000") {
          this.userTableData = res.retBody.list;
          this.total1 = res.retBody.total;
          this.currentPage1 = res.retBody.pageNum;
        } else {
          this.$message.error("发生错误！");
        }
      });
    },
    handleAdd() {
      this.form.sysOrganList = this.sysOrganList;
      this.form.dutyEnabledState = this.switchValue;
      this.$refs.addForm.validate(valid => {
        if (valid) {
          this.$api.post("/api/auth/sysDuty/doSave", this.form).then(res => {
            if (res.retHead.code == "0000000") {
              this.$message({
                message: "添加成功！",
                type: "success"
              });
              this.dialogFormVisible = false;
              this.init();
            } else {
              this.$message({
                message: res.retHead.message,
                type: "error"
              });
            }
          });
        }
      });
    },
    handleEdit() {
      this.$refs.editForm.validate(valid => {
        if (valid) {
          this.editForm.sysOrganList = this.sysOrganList;
          this.editForm.dutyEnabledState = this.switchEditValue;
          this.$api
            .post("/api/auth/sysDuty/doModById", this.editForm)
            .then(res => {
              if (res.retHead.code == "0000000") {
                this.$message.success("执行成功！");
                this.init();
                this.dialogEditVisible = false;
              } else {
                this.$message.error(res.retHead.message);
              }
            });
        }
      });
    },
    getusers() {
      let params = {};
      this.$api.formPost("/api/auth/sysuser/doGetList", params).then(res => {
        if (res.retHead.code == "0000000") {
          this.users = res.retBody.list;
        }
      });
    },
    handleDelete(index, row) {
      this.$confirm("此操作将永久删除该项, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$api
            .formPost("/api/auth/sysDuty/doRmById", {
              id: row.id
            })
            .then(res => {
              if (res.retHead.code == "0000000") {
                this.$message({
                  message: "删除成功！",
                  type: "success"
                });
                this.init();
              } else {
                this.$message({
                  message: "删除失败！",
                  type: "error"
                });
              }
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    submitForm(formName) {
      this.init();
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  },
  created() {}
};
</script>
<style lang='scss' scoped>
.btns {
  text-align: right;
}

.icon-arrow {
  position: absolute;
  bottom: 5px;
  left: 0;
  width: 100%;
  height: 1px;
  background-color: #f1f1f1;

  i {
    background-color: #fff;
    position: absolute;
    color: #999;
    bottom: -7px;
    margin-left: 50%;
    transform: translateX(-50%);
    cursor: pointer;
  }
}
</style>